package cn.bud.msgbus.consumer.bean;

import cn.hutool.core.collection.ConcurrentHashSet;
import lombok.Data;

import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Subscriber
 *
 * @author hxj
 * @version 1.0
 * @description
 * @date 2024-06-19 14:14
 */
@Data
public abstract class Subscriber {
    /**
     * 标题
     * key 标题
     * value 有效时间段，0:开始时间 1:结束时间
     */
    protected Map<String, LocalDateTime[]> topics;


    public void addTopic(String topic, LocalDateTime startTime, LocalDateTime endTime) {
        if (topics == null) {
            topics = new ConcurrentHashMap<>();
        }
        topics.put(topic, new LocalDateTime[]{startTime, endTime});
    }

    public Collection<String> topicSet() {
        if (topics == null) {
            return new ConcurrentHashSet<>();
        }
        return topics.keySet();
    }

    public boolean isTimeUnEffect(String topic) {
        return !isTimeEffect(topic);
    }

    /**
     * 当前时间是否在推送时间段内
     * @return
     */
    public boolean isTimeEffect(String topic) {
        if (topics == null || !topics.containsKey(topic)) {
            return false;
        }
        LocalDateTime[] condTimes = topics.get(topic);
        if (condTimes[0] == null && condTimes[1] == null) {
            return true;
        }
        LocalDateTime nowTime = LocalDateTime.now();
        if (condTimes[0] != null && nowTime.isBefore(condTimes[0])) {
            return false;
        }
        if (condTimes[1] != null && nowTime.isAfter(condTimes[1])) {
            return false;
        }
        return true;
    }

    public abstract String name();



    /**
     *  下发消息给订阅用户
     * @param msg
     */
    public abstract void sendMsg(MsgBody msg) throws Exception;
}
